﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

class RC4Encryption
{
    private byte[] key;
    private static Random rand = new Random();
    private int positionEncrypted;
    private int positionDecrypted;
    public RC4Encryption()
    {
        positionEncrypted = 0;
        positionDecrypted = 0;
        key = new byte[rand.Next() % 256];
        for (int i = 0; i < key.Length; i++)
        {
            key[i] = (byte)(rand.Next() % 256);
        }
    }

    public byte[] Encrypt(byte[] bytes)
    {
        byte[] encrypted = new byte[bytes.Length];

        for (int i = 0; i < bytes.Length; i++)
        {
            encrypted[i] = (byte)(bytes[i] ^ key[positionEncrypted]);
            positionEncrypted++;
            positionEncrypted %= key.Length;
        }
        return encrypted;
    }

    public byte[] Decrypt(byte[] bytes)
    {
        byte[] decrypted = new byte[bytes.Length];

        for (int i = 0; i < bytes.Length; i++)
        {
            decrypted[i] = (byte)(bytes[i] ^ key[positionDecrypted]);
            positionDecrypted++;
            positionDecrypted %= key.Length;
        }
        return decrypted;
    }

    static void Main(string[] args)
    {
        string inputFile = "test.txt";
        string encryptedFile = "test.enc";
        string decryptedFile = "test.dec";
        RC4Encryption rc4 = new RC4Encryption();

        using (FileStream input = new FileStream(inputFile, FileMode.Open))
        {
            using (FileStream output = new FileStream(encryptedFile, FileMode.Create))
            {
                byte[] buff = new byte[4096];
                while (true)
                {
                    int bytesRead = input.Read(buff, 0, buff.Length);
                    if (bytesRead == 0)
                    {
                        break;
                    }

                    output.Write(rc4.Encrypt(buff), 0, bytesRead);
                }
            }
        }

        using (FileStream input = new FileStream(encryptedFile, FileMode.Open))
        {
            using (FileStream output = new FileStream(decryptedFile, FileMode.Create))
            {
                byte[] buff = new byte[4096];
                while (true)
                {
                    int bytesRead = input.Read(buff, 0, buff.Length);
                    if (bytesRead == 0)
                    {
                        break;
                    }

                    output.Write(rc4.Decrypt(buff), 0, bytesRead);
                }
            }
        }
    }
}
